package com.zb.utils;

import cn.dev33.satoken.router.SaRouter;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.constant.HeaderConstant;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author WEN
 * @Date 2023/7/29 0029
 **/
public class RequestUtil {

    /**
     * 从上下文中获取 HttpServletRequest 对象
     * @return
     */
    public static HttpServletRequest getRequestByContext() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return  ((ServletRequestAttributes)requestAttributes).getRequest();
    }

    /**
     * 请求路径是否为工单报单移动端
     * @return
     */
    public static boolean isMobileUser() {
        String uri = getRequestByContext().getRequestURI();
        return isMobile() && uri.startsWith("/mobile/user/");
    }

    /**
     * 请求路径是否为服务商移动端
     * @return
     */
    public static boolean isMobileNetwork() {
        String uri = getRequestByContext().getRequestURI();
        return isMobile() && uri.startsWith("/mobile/network/");
    }

    /**
     * 是否共同的移动端路径
     * @return
     */
    public static boolean isPublicMobile() {
        List<String> paths = new ArrayList<>();
        paths.add("/mobile/select/**");
        paths.add("/mobile/file");
        paths.add("/file/delete/mobile");
        paths.add("/mobile/identify/**");
        paths.add("/callback/**");
        return SaRouter.match(paths).isHit;
    }

    /**
     * 是否客户移动端登录配置查询
     * @return
     */
    public static boolean isUserMobileLogin() {
        List<String> paths = new ArrayList<>();
        paths.add("/mobile/user/getMobileUserHasLogin");
        return SaRouter.match(paths).isHit;
    }

    /**
     * 客户移动端是否必须登录，从请求头中获取标识
     * @return
     */
    public static boolean isUserMobileHasLogin() {
        HttpServletRequest request = getRequestByContext();
        String mobileUserHasLogin = request.getHeader(HeaderConstant.HEADER_USER_MOBILE_HAS_LOGIN);
        boolean flag = true; // 默认需要登录
        if (StringUtils.isNotBlank(mobileUserHasLogin) && Objects.equals(HeaderConstant.HEADER_USER_MOBILE_HAS_LOGIN_NO_LOGIN, mobileUserHasLogin)) {
            flag = false;
        }
        return flag;
    }

    /**
     * 是否pc端
     * @return
     */
    public static boolean isPc() {
        return !isMobile();
    }


    /**
     * 是否移动端
     * @return
     */
    private static boolean isMobile() {
        HttpServletRequest request = getRequestByContext();
        String uri = request.getRequestURI();
        return uri.startsWith("/mobile/");
    }





}
